package logic

import (
	"context"
	"strings"
	"time"

	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateRoleLogic {
	return &BackendCreateRoleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendCreateRoleLogic) BackendCreateRole(in *backend.CreateRoleRequest) (*backend.CreateRoleResponse, error) {
	if len(strings.TrimSpace(in.Name)) == 0 {
		return nil, errorx.Status(errorx.ERROR_ROLE_NAME_REQUIRED, "")
	}

	_, count, err := l.svcCtx.BackendRole.GetList(l.ctx, model.M{
		model.BackendRoleColumns.Name: in.Name,
	}, 0)
	if err != nil {
		return nil, err
	}
	if count > 0 {
		return nil, errorx.Status(errorx.ERROR_ROLE_NAME_EXISTS, "")
	}

	var role model.BackendRole
	role.Name = in.Name
	role.Note = in.Note
	role.Status = uint8(in.Status)
	role.DelStatus = uint8(in.Status)
	role.CreatedBy = uint64(in.CreatedBy)
	role.LastUpdatedBy = uint64(in.CreatedBy)
	role.CreatedAt = time.Now()
	role.UpdatedAt = time.Now()

	err = l.svcCtx.BackendRole.Insert(l.ctx, &role)
	if err != nil {
		return nil, err
	}

	return &backend.CreateRoleResponse{}, nil
}
